package me.mingshan.leetcode;

/**
 * @author hanjuntao
 * @date 2025/5/30 0030
 */
public class L_278_first_bad_version extends VersionControl {

    public static void main(String[] args) {
        int n = 5;
        int bad = 4;
        L_278_first_bad_version l = new L_278_first_bad_version();
        l.setBad(bad);
        System.out.println(l.firstBadVersion(n));
    }


    /**
     * 思路：二分查找
     *
     *
     *
     * @param n
     * @return
     */
    public int firstBadVersion(int n) {
        int left = 0;
        int right = n;

        while (left <= right) {
            int mid = left + (right - left) / 2;
            boolean badVersion = isBadVersion(mid);
            if (badVersion) {
                // 找到第一个错误版本
                // 当前的版本再往上找一个，如果是正常版本，说明当前为第一个错误版本
                if (mid == 0 || !isBadVersion(mid - 1)) {
                    return mid;
                } else {
                    right = mid - 1;
                }
            } else {
                left = mid + 1;
            }
        }

        return -1;
    }
}
